﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ElectronicJournal.Account.AuthorAccount
{
    public partial class ReloadPublication : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                var publicationId = Request.Params["pubId"];
                if(publicationId!=null)
                {
                    var pubGuid = Guid.Parse(publicationId.ToString());
                    var currentPub = EJournalRepository.Instance.GetPublicationById(pubGuid);
                    ViewState["PubId"] = pubGuid;
                }
            }
        }

        private static int verCounter = 0;
        protected void OkBtn_Click(object sender, EventArgs e)
        {
            var pubId = Guid.Parse(ViewState["PubId"].ToString());
            var folderToSaveIn = Server.MapPath(@"..\") + @"\files\publications\";
            var resultPath = UploadFileOnServer(PublicationReloadUpload, folderToSaveIn, pubId);
            EJournalRepository.Instance.ChangePublicationFile(pubId, resultPath);
            EJournalRepository.Instance.RefreshArticleState(1,pubId);
            //EJournalRepository.Instance.SaveRecieptNumberPublications(pubId, UploadFileOnServer(PublicationReloadUpload, folderToSaveIn));
            Response.Redirect("MyAccount.aspx");
        }

        private string UploadFileOnServer(FileUpload uploader, string folder, Guid pubGuid)
        {
            //System.IO.Directory.CreateDirectory(folder);
            string FileName = System.IO.Path.GetFileName(uploader.FileName);
            var location = folder + Path.GetFileNameWithoutExtension(FileName) +
                           "_" + pubGuid.ToString() +
                           "_ver" + ++verCounter + Path.GetExtension(FileName);
            if ((uploader.PostedFile != null))
            {
                uploader.PostedFile.SaveAs(location);
            }
            return Path.GetFileName(location);
        }


        protected void BackBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("MyAccount.aspx");
        }

    }
}